﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;

namespace BizElements.Generator
{
    static class IoUtil
    {
        /// <summary>Converts input path to absolute path or returns null if path is invalid.</summary>
        public static string ToAbsFilePath(string absOrRelativeFilePath)
        {
            if (!IsValidFilePath(absOrRelativeFilePath))
                return null;

            string absPath;
            if (Path.IsPathRooted(absOrRelativeFilePath))
                absPath = absOrRelativeFilePath;
            else
                absPath = GetExecutableDirectoryWithSeparator() + absOrRelativeFilePath;

            return absPath;
        }

        public static string GetExecutableFilePath()
        {
            return Assembly.GetEntryAssembly().Location;
        }

        public static string GetExecutableDirectory()
        {
            string exePath = GetExecutableFilePath();
            return Path.GetDirectoryName(exePath);
        }

        public static string GetExecutableDirectoryWithSeparator()
        {
            string exeDir = GetExecutableDirectory();
            return TextUtil.EnsureSuffix(exeDir, Path.DirectorySeparatorChar.ToString());
        }

        /// <summary>Checks whether the provided path is valid.</summary>
        public static bool IsValidFilePath(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return false;
            }
            else
            {
                foreach (char invalid in Path.GetInvalidPathChars())
                {
                    if (filePath.Contains(invalid.ToString()))
                        return false;
                }
            }

            return true;
        }
    }
}
